/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 * Date: 2024-03-04
 * Time: 10:08
 */
public class Sort1 {
    public static  void bubbleSort(int[] array){
        for (int i = 0; i < array.length -1; i++) {
            for (int j = 0; j < array.length -1-i; j++) {
                if(array[j]>array[j+1]){
                    swap(array,j,j+1);
                }
            }
        }
    }

    private static void swap(int[] array, int j, int i) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void insetSort(int[] array){
        for (int i = 1; i < array.length; i++) {
            int temp = array[i];
            int j=i-1;
            for (; j >= 0; j--) {
                if(array[j] > temp){
                    array[j+1]= array[j];
                }else{
                    break;
                }
            }
            array[j+1] =temp;
        }
    }

    public static void selectSort(int[] array){
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < array.length; j++) {
                if(array[j]< array[minIndex]){
                    minIndex = j;
                }
            }
            swap(array,i,minIndex);
        }
    }

    public static void heapSort(int[] array){
        createBigHeap(array);
        int end = array.length - 1;
        while(end>0){
            swap(array,end,0);
            shiftDown(array,0,end);
            end--;
        }
    }

    private static void createBigHeap(int[] array) {
        for (int i =(array.length-1-1)/2; i>=0; i--) {
            shiftDown(array,i, array.length);
        }
    }

    private static void shiftDown(int[] array, int parent, int len) {
        int child  =parent*2 + 1;
        while(child<len){
            if(child+1<len && array[child]<array[child+1]){
                child=child+1;
            }
            if(array[child]>array[parent]){
                swap(array,child,parent);
                parent=child;
                child=parent*2+1;
            }else{
                break;
            }
        }
    }

}
